import {
	API$GetFolderList,
	API$UploadFile,
	API$SyncUploadFile,
	API$GetUploadRecordList
} from '../../common/API/file.js';
// 上传图片（uni.uploadFile的方法）
let RenderUpload_img = async function(that, res, currentUploadPath) {
	/*
	@ 	that 				Vue实例
	@	res					选择文件返回的数据
	@	currentUploadPath	要上传的oss路径
	*/
	console.log('选择相册返回的数据：', res);
	let tempFilePaths = res.tempFilePaths; // 一般是9张
	for (let i = 0; i < tempFilePaths.length; i++) {
		let id = that.$tool.create_token(); // 文件id
		let pathName, FileType, fileName, fileType, filePath, fileSize, uploadTask_filePath;
		// #ifdef APP-PLUS
		pathName = tempFilePaths[i].split('/')[tempFilePaths[i].split('/').length - 1]; //	文件名字哦.video
		FileType = that.$tool.getFileType(pathName); //	文件后缀名（.video）
		// console.log(currentUploadPath + (res.tempFiles[i].name || pathName));
		// #endif

		fileName = res.tempFiles[i].name || pathName; // 文件名字
		fileType = res.tempFiles[i].type || FileType; // 文件类型
		filePath = currentUploadPath + (res.tempFiles[i].name || pathName); // 文件路径（oss上传路径）
		fileSize = res.tempFiles[i].size; // 文件大小
		uploadTask_filePath = tempFilePaths[i]; // 本地文件路径		

		//  H5和app的上传 都放在一起了
		// 上传文件记录
		let {
			code,
			msg,
			params
		} = await API$UploadFile({
			fileId: id,
			fileName,
			fileType,
			filePath,
			fileSize
		});
		if (code === 204) {
			return that.$pub.Toast(msg)
		}

		// 上传对象
		let fileObj = {
			progressTime: null, // 节流计时
			LastSecondSize: 0, // 上一秒已下载的量
			timer: null, // 轮询定时器（定时同步接口）
			LocalPath: uploadTask_filePath, // 本地图片地址回显

			fileName,
			fileSize,
			fileType,
			id,
			lastModifiedDate: res.tempFiles[i].lastModifiedDate,
			progress: 0,
			currentTotal: 0,
			total: 0,
			Speed: 0, // 下载速度(字节为单位)
			SyncTime: that.$tool.create_time(new Date(), 'YYYYMMMDDHHMMSS'),
			uploadTask: null
		};
		that.$store.commit('ADD_UploadTask', fileObj);
		fileObj.uploadTask = uni.uploadFile({
			url: 'https://' + params.host,
			filePath: uploadTask_filePath,
			name: 'file',
			formData: {
				key: params.ROOT_dir + '/' + currentUploadPath + fileName,
				policy: params.policy,
				OSSAccessKeyId: params.OSSAccessKeyId,
				success_action_status: '200',
				Signature: params.signature
				// 'x-oss-security-token': that.$store.state.file.StsConfig.stsToken // 使用STS签名时必传。
			},
			success: async uploadFileRes => {
				if (uploadFileRes.statusCode == 200) {
					await API$SyncUploadFile({
						fileId: fileObj.id,
						progress: 100
					});
					that.$pub.Toast('上传成功~');
					that.$store.commit('ADD_CompleteUploadTask_id', id);
					// uni.$emit('FreshGetRecodList'); // 不能刷新  我的上传种的记录还没做
					// that.$store.commit('DEL_UploadTask', id);
					//	oss推荐后台读，前台获取不到访问路径
					//	tempFilePaths可以回显图片
					// console.log(tempFilePaths);
				}
				if (uploadFileRes.statusCode == 413) {
					uni.showToast({
						title: '图片过大',
						icon: 'none',
						duration: 4000
					});
				}
			},
			fail: error => {
				console.log(error);
			},
			complete: () => {
				console.log('完成（不论成功失败~）');
				clearInterval(fileObj.timer);
			}
		})
		if (!fileObj.timer) {
			fileObj.timer = setInterval(async () => {
				let SyncUp = await API$SyncUploadFile({
					fileId: fileObj.id,
					progress: fileObj.progress
				});
				console.log('定时器', SyncUp);
			}, 5000);
		}
		fileObj.uploadTask.onProgressUpdate(function(res) {
			// 节流操作
			if (fileObj.progressTime) return
			fileObj.progressTime = setTimeout(() => {
				fileObj.currentTotal = that.$tool.comFileSize(res.totalBytesSent);
				fileObj.Speed = res.totalBytesSent - fileObj.LastSecondSize;
				fileObj.total = that.$tool.comFileSize(res.totalBytesExpectedToSend);
				fileObj.progress = res.progress;
				// console.log('上传进度' + res.progress,fileObj.currentTotal,fileObj.total);
				fileObj.LastSecondSize = res.totalBytesSent // 便于计算速度
				clearTimeout(fileObj.progressTime)
				fileObj.progressTime = null
			}, 1000)

			// console.log('已经上传的数据长度' + that.$tool.comFileSize(res.totalBytesSent));
			// console.log('预期需要上传的数据总长度' + that.$tool.comFileSize(res.totalBytesExpectedToSend));
		});
	}
	that.$pub.redirTo('/pages/public/TransferPopup/TransferManager'); // 跳转页面
}

// 上传视频（uni.uploadFile的方法）
let RenderUpload_video = async function(that, res, currentUploadPath) {
	let id = that.$tool.create_token(); // 创建唯一id

	// #ifdef APP-PLUS
	let fileName = res.tempFilePath.split('/')[res.tempFilePath.split('/').length - 1]; // "file:///storage/emulated/0/Pictures/WeiXin/wx_camera_1601518328563.mp4",
	let fileType = that.$tool.getFileType(fileName);
	let fileSize = res.size;
	let filePath = currentUploadPath + fileName;
	let lastModifiedDate = new Date().getTime();
	// #endif

	// #ifdef H5
	let fileName = res.name,
		fileType = that.$tool.getFileType(res.name),
		fileSize = res.size,
		filePath = currentUploadPath + res.name,
		lastModifiedDate = res.tempFile.lastModifiedDate;
	// #endif

	// 上传文件记录
	let {
		code,
		msg,
		params
	} = await API$UploadFile({
		fileId: id,
		fileName,
		fileSize,
		fileType,
		filePath
	});

	if (code === 204) {
		return that.$pub.Toast(msg)
	}

	//  H5和app的 上传 都放在一起了
	// 上传对象
	let fileObj = {
		progressTime: null, // 节流计时
		LastSecondSize: 0, // 上一秒已下载的量
		timer: null, // 轮询定时器（定时同步接口）


		fileName,
		fileSize,
		fileType,
		id,
		lastModifiedDate,
		progress: 0,
		currentTotal: 0,
		total: 0,
		Speed: 0, // 下载速度(字节为单位)
		SyncTime: that.$tool.create_time(new Date(), 'YYYYMMMDDHHMMSS'),
		uploadTask: null
	};
	that.$store.commit('ADD_UploadTask', fileObj);
	fileObj.uploadTask=uni.uploadFile({
		url: 'https://' + params.host,
		filePath: res.tempFilePath,
		name: 'file',
		formData: {
			key: params.ROOT_dir + '/' + currentUploadPath + fileName,
			policy: params.policy,
			OSSAccessKeyId: params.OSSAccessKeyId,
			success_action_status: '200',
			Signature: params.signature
			// 'x-oss-security-token': that.$store.state.file.StsConfig.stsToken // 使用STS签名时必传。
		},
		success: async uploadFileRes => {
			// uni.hideLoading();
			if (uploadFileRes.statusCode == 200) {
				let c = await API$SyncUploadFile({
					fileId: fileObj.id,
					progress: 100
				});
				that.$pub.Toast('上传成功~');
				that.$store.commit('ADD_CompleteUploadTask_id', id);

				// 刷新数据
				// let res = await API$GetUploadRecordList();
				// console.log('666666666666666666666666666666666',res)
				// that.$store.commit('CHANGE_CompleteUploadTask', res.result.data);

				//oss推荐后台读，前台获取不到访问路径
				//tempFilePaths可以回显图片
				// console.log(tempFilePaths);
			}
			if (uploadFileRes.statusCode == 413) {
				uni.showToast({
					title: '文件过大',
					icon: 'none',
					duration: 4000
				});
			}
		},
		fail: error => {
			console.log(error);
		},
		complete: () => {
			console.log('完成（不论成功失败~）');
			clearInterval(fileObj.timer);
		}
	})
	if (!fileObj.timer) {
		fileObj.timer = setInterval(async () => {
			let SyncUp = await API$SyncUploadFile({
				fileId: fileObj.id,
				progress: fileObj.progress
			});
			console.log('定时器', SyncUp);
			console.log('定时器', fileObj.progress);
		}, 5000);
	}
	fileObj.uploadTask.onProgressUpdate(function(res) {
		// 节流操作
		if (fileObj.progressTime) return
		fileObj.progressTime = setTimeout(() => {
			fileObj.currentTotal = that.$tool.comFileSize(res.totalBytesSent);
			fileObj.Speed = res.totalBytesSent - fileObj.LastSecondSize;
			fileObj.total = that.$tool.comFileSize(res.totalBytesExpectedToSend);
			fileObj.progress = res.progress;
			fileObj.LastSecondSize = res.totalBytesSent // 便于计算速度
			clearTimeout(fileObj.progressTime)
			fileObj.progressTime = null
		}, 1000)
	});
	that.$pub.redirTo('/pages/public/TransferPopup/TransferManager'); // 跳转页面
}

// 上传图片（plus的方法）
let PlusUpload_img = async function(that, res, currentUploadPath) {
	/*
	@ 	that 				Vue实例
	@	res					选择文件返回的数据
	@	currentUploadPath	要上传的oss路径
	*/
	console.log('选择相册返回的数据：', res);
	let tempFilePaths = res.tempFilePaths; // 一般是9张
	for (let i = 0; i < tempFilePaths.length; i++) {
		let id = that.$tool.create_token(); // 文件id
		let pathName, FileType, fileName, fileType, filePath, fileSize, uploadTask_filePath;
		// #ifdef APP-PLUS
		pathName = tempFilePaths[i].split('/')[tempFilePaths[i].split('/').length - 1]; //	文件名字哦.video
		FileType = that.$tool.getFileType(pathName); //	文件后缀名（.video）
		// console.log(currentUploadPath + (res.tempFiles[i].name || pathName));
		// #endif
	
		fileName = res.tempFiles[i].name || pathName; // 文件名字
		fileType = res.tempFiles[i].type || FileType; // 文件类型
		filePath = currentUploadPath + (res.tempFiles[i].name || pathName); // 文件路径（oss上传路径）
		fileSize = res.tempFiles[i].size; // 文件大小
		uploadTask_filePath = tempFilePaths[i]; // 本地文件路径		
	
		//  H5和app的上传 都放在一起了
		// 上传文件记录
		let {
			code,
			msg,
			params
		} = await API$UploadFile({
			fileId: id,
			fileName,
			fileType,
			filePath,
			fileSize
		});
		if (code === 204) {
			return that.$pub.Toast(msg)
		}
	
		// 上传对象
		let fileObj = {
			progressTime: null, // 节流计时
			LastSecondSize: 0, // 上一秒已下载的量
			timer: null, // 轮询定时器（定时同步接口）
			LocalPath: uploadTask_filePath, // 本地图片地址回显
	
			fileName,
			fileSize,
			fileType,
			id,
			lastModifiedDate: res.tempFiles[i].lastModifiedDate,
			progress: 0,
			currentTotal: 0,
			total: 0,
			Speed: 0, // 下载速度(字节为单位)
			SyncTime: that.$tool.create_time(new Date(), 'YYYYMMMDDHHMMSS'),
			uploadTask:plus.uploader.createUpload(
				'https://' + params.host, 
				{ method:"POST"}, 
				async function ( upload, status ) {
					// 这个回调无论失败与否都会调用
					if(upload.state===4 && (status===204 || status===200)){
						await API$SyncUploadFile({
							fileId: fileObj.id,
							progress: 100
						});
						that.$pub.Toast('上传成功~');
						that.$store.commit('ADD_CompleteUploadTask_id', id);
					}
					clearInterval(fileObj.timer);  // 清空定时器
				} 
			)
		}	
		fileObj.uploadTask.addData( "key", params.ROOT_dir + '/' + currentUploadPath + fileName );
		fileObj.uploadTask.addData( "policy", params.policy );
		fileObj.uploadTask.addData( "OSSAccessKeyId",  params.OSSAccessKeyId );
		fileObj.uploadTask.addData( "success_action_status",  200);
		fileObj.uploadTask.addData( "Signature",  params.signature);
		fileObj.uploadTask.addFile(uploadTask_filePath, {key: "file" });
		// fileObj.uploadTask.addData( "x-oss-security-token", that.$store.state.file.StsConfig.stsToken);
		fileObj.uploadTask.start();
		fileObj.uploadTask.addEventListener( "statechanged", function( upload, status){
			// 节流操作
			fileObj.currentTotal = that.$tool.comFileSize(upload.uploadedSize);  // 当前上传的量
			fileObj.Speed = upload.uploadedSize - fileObj.LastSecondSize;
			fileObj.total = that.$tool.comFileSize(upload.totalSize);			 // 总的上传的量
			fileObj.progress = parseInt((upload.uploadedSize / upload.totalSize) * 100);
			fileObj.LastSecondSize = upload.uploadedSize // 便于计算速度
			clearTimeout(fileObj.progressTime)
			fileObj.progressTime = null
			return
			switch(upload.state){
				case undefined:
					console.log('上传任务未开始')
					break;
				case 2:
					console.log('上传任务请求已经建立')
					break;
				case 0:
					console.log('上传任务开始调度')
					break;
				case 1:
					console.log('上传任务开始请求')
					break;
				case 3:
					console.log(`上传任务提交数据,uploadedSize:${upload.uploadedSize},totalSize:${upload.totalSize}`)
					break;
				case 4:
					console.log('上传任务已完成')
					break;
				case 5:
					console.log('上传任务已暂停')
					break;
				case -1:
					console.log('枚举任务状态')
					break;
			}
		}, false);
		that.$store.commit('ADD_UploadTask', fileObj);
		if (!fileObj.timer) {
			fileObj.timer = setInterval(async () => {
				let SyncUp = await API$SyncUploadFile({
					fileId: fileObj.id,
					progress: fileObj.progress
				});
				console.log('定时器', SyncUp);
			}, 5000);
		}
	}
	that.$pub.redirTo('/pages/public/TransferPopup/TransferManager'); // 跳转页面
}

// 上传视频（plus的方法）
let PlusUpload_video = async function(that, res, currentUploadPath) {
	let id = that.$tool.create_token(); // 创建唯一id
	
	// #ifdef APP-PLUS
	let fileName = res.tempFilePath.split('/')[res.tempFilePath.split('/').length - 1]; // "file:///storage/emulated/0/Pictures/WeiXin/wx_camera_1601518328563.mp4",
	let fileType = that.$tool.getFileType(fileName);
	let fileSize = res.size;
	let filePath = currentUploadPath + fileName;
	let lastModifiedDate = new Date().getTime();
	// #endif
	
	// #ifdef H5
	let fileName = res.name,
		fileType = that.$tool.getFileType(res.name),
		fileSize = res.size,
		filePath = currentUploadPath + res.name,
		lastModifiedDate = res.tempFile.lastModifiedDate;
	// #endif
	
	// 上传文件记录
	let {
		code,
		msg,
		params
	} = await API$UploadFile({
		fileId: id,
		fileName,
		fileSize,
		fileType,
		filePath
	});
	if (code === 204) {
		return that.$pub.Toast(msg)
	}
	
	//  H5和app的 上传 都放在一起了
	// 上传对象
	let fileObj = {
		progressTime: null, // 节流计时
		LastSecondSize: 0, // 上一秒已下载的量
		timer: null, // 轮询定时器（定时同步接口）
	
	
		fileName,
		fileSize,
		fileType,
		id,
		lastModifiedDate,
		progress: 0,
		currentTotal: 0,
		total: 0,
		Speed: 0, // 下载速度(字节为单位)
		SyncTime: that.$tool.create_time(new Date(), 'YYYYMMMDDHHMMSS'),
		uploadTask:plus.uploader.createUpload(
			'https://' + params.host, 
			{ method:"POST",blocksize:0}, 
			async function ( upload, status ) {
				console.log('这个回调无论失败与否都会调用',upload, status)
				// 这个回调无论失败与否都会调用
				if(upload.state===4 && (status===204 || status===200)){
					await API$SyncUploadFile({
						fileId: fileObj.id,
						progress: 100
					});
					that.$pub.Toast('上传成功~');
					that.$store.commit('ADD_CompleteUploadTask_id', id);
				}
				clearInterval(fileObj.timer);  // 清空定时器
			} 
		)
	};
	
	fileObj.uploadTask.addData( "key", params.ROOT_dir + '/' + currentUploadPath + fileName );
	fileObj.uploadTask.addData( "policy", params.policy );
	fileObj.uploadTask.addData( "OSSAccessKeyId",  params.OSSAccessKeyId );
	fileObj.uploadTask.addData( "success_action_status",  200);
	fileObj.uploadTask.addData( "Signature",  params.signature);
	fileObj.uploadTask.addFile(res.tempFilePath, {  
		key: 'file',  
		name: 'file',  
		mime: `video/${fileType}`
	});
	// fileObj.uploadTask.setRequestHeader("application/video/mp4");
	// fileObj.uploadTask.setRequestHeader("application/octet-stream");
	// fileObj.uploadTask.addData( "x-oss-security-token", that.$store.state.file.StsConfig.stsToken);
	that.$store.commit('ADD_UploadTask', fileObj);
	setTimeout(()=>{
		fileObj.uploadTask.start();
		fileObj.uploadTask.addEventListener( "statechanged", function( upload, status){
			// 节流操作
			fileObj.currentTotal = that.$tool.comFileSize(upload.uploadedSize);  // 当前上传的量
			fileObj.Speed = upload.uploadedSize - fileObj.LastSecondSize;
			fileObj.total = that.$tool.comFileSize(upload.totalSize);			 // 总的上传的量
			fileObj.progress = parseInt((upload.uploadedSize / upload.totalSize) * 100);
			// console.log('进度：',fileObj.progress)
			fileObj.LastSecondSize = upload.uploadedSize // 便于计算速度
			// clearTimeout(fileObj.progressTime)
			// fileObj.progressTime = null
			return
			// if (fileObj.progressTime) return
			// fileObj.progressTime = setTimeout(() => {
				
			// }, 100)
			switch(upload.state){
				case undefined:
					console.log('上传任务未开始')
					break;
				case 2:
					console.log('上传任务请求已经建立')
					break;
				case 0:
					console.log('上传任务开始调度')
					break;
				case 1:
					console.log('上传任务开始请求')
					break;
				case 3:
					console.log(`上传任务提交数据,uploadedSize:${upload.uploadedSize},totalSize:${upload.totalSize}`)
					break;
				case 4:
					console.log('上传任务已完成')
					break;
				case 5:
					console.log('上传任务已暂停')
					break;
				case -1:
					console.log('枚举任务状态')
					break;
			}
		}, false);
		
		
		if (!fileObj.timer) {
			fileObj.timer = setInterval(async () => {
				let SyncUp = await API$SyncUploadFile({
					fileId: fileObj.id,
					progress: fileObj.progress
				});
				console.log('定时器', SyncUp);
			}, 5000);
		}
	},1000)
	that.$pub.redirTo('/pages/public/TransferPopup/TransferManager'); // 跳转页面
}
export default {
	RenderUpload_img,
	RenderUpload_video,
	PlusUpload_img,
	PlusUpload_video
}
